package com.seestech.sell.web.cloudDisk;

import com.alibaba.fastjson.JSONArray;
import com.seestech.sell.common.annotation.RecordLog;
import com.seestech.sell.common.config.ApplicationConfig;
import com.seestech.sell.common.utils.*;
import com.seestech.sell.domain.model.Directory;
import com.seestech.sell.domain.model.ResultBean;
import com.seestech.sell.domain.model.User;
import com.seestech.sell.domain.model.enums.StatusEnums;
import com.seestech.sell.service.IDirectoryService;
import com.seestech.sell.service.IFileService;
import com.seestech.sell.web.SuperController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Set;


/**
 *ted by idiot on 2017/8/2.
 * @description  目录相关接口
 */
@Controller
@RequestMapping(value = "cloudDisk/directory")
public class DirectoryController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(DirectoryController.class);

    @Resource
    private IDirectoryService directoryService;
    @Resource
    private IFileService fileService;
    @Resource
    private ApplicationConfig applicationConfig;

    //加载page页面
    @RecordLog(value = "目录信息页面")
    @RequiresPermissions(value = "cloudDisk:directory:page")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    public String toEdit(Model model){
        logger.info("目录信息页面................");
        return "cloudDisk/directory/page";
    }

    //前往编辑目录页面
    @RecordLog(value = "前往编辑目录信息")
    @RequestMapping(value = "toAdd", method = RequestMethod.POST)
    public String toAdd(Model model){
        return "cloudDisk/directory/update";
    }

    //前往编辑页面
    @RequestMapping(value = "toUpdate", method = RequestMethod.GET)
    public String toAdd(Model model, Directory info){
        //如果父级编号不存在 加载所有的父级目录
        if(info.getParentDirectoryId() == null){
            if(info.getType() == 2){    //当Type为2 时 表示是加载个人素材库
                info.setCreateUser(getUser().getUserId());      //设置当前用户
            }
            List<Directory> parentDiretories = directoryService.getDirectoriesByDirectory(info);
            model.addAttribute("parentDiretories", parentDiretories);
        }else {
            //先判断该目录是第几级  如果是3级目录就不能新增了
            int level = directoryService.getLevelByDirectoryId(info.getParentDirectoryId());
            if(level >= 3){
                logger.error("前往新建目录页面======>>>>>目录等级最多三级=====>>>"+level);
                model.addAttribute("msg", "目录最多支持三级");
                return "error";
            }
            Directory directory = directoryService.getDirectoryByDirectoryId(info.getParentDirectoryId());
            model.addAttribute("parentDirectory", directory);
        }
        model.addAttribute("type", info.getType());
        return "cloudDisk/directory/update";
    }

    //编辑目录信息 可新增  可修改（目录名）
    @RecordLog(value = "修改目录信息")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public void update(Model model, Directory info){
        //directoryId为空时表示   新增操作
        if(info.getDirectoryId() == null){
            info.setCreateUser(getUser().getUserId());      //设置创建用户
            info.setPathCode(EncodeMD5.GetMD5Code(String.valueOf(IdGen.get().nextId())));   //为避免目录覆盖 由系统生成
            directoryService.insert(info);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "新增目录信息成功");
        }else {     //修改操作
            directoryService.update(info);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "修改目录信息成功");
        }
    }

    //删除目录信息
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public void delDirectory(Long directoryId){
        Directory directory = directoryService.getDirectoryByDirectoryId(directoryId);
        if(directory != null){
            //获取目录路径
            String dir = directoryService.getDirectoryPathBydirectoryId(directoryId);
            dir = FileUtils.addPathSeparate(applicationConfig.getBaseDirectory(), dir);
            FileUtils.deleteDirectory(new File(FileUtils.getWindowsPath(dir)));
            //删除文件 和 目录信息
            fileService.deleteFilesByDirectoryId(directoryId);
            directoryService.delete(directoryId);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "删除目录信息成功");
        }else {
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "删除目录信息失败");
        }
    }


    /******************************* 接口 *****************************************/

    /**
     * @description  获取目录信息接口
     * @param info
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getDirectories.json")
    public Object getDirectories(Directory info){
        ResultBean<Object> resultBean;
        logger.info("获取目录信息接口============>>>>>>>>>【开始】");
        User user = getUser();
        if(user == null){
            logger.error("获取目录信息接口======>>>>>>>>用户信息失效，请重新登录");
            return ResponseUtils.initResultBean(null, Constants.ResponseCode.invalid_user, "用户信息失效，请重新登录", false);
        }
        if(info.getStatus() == null)
            info.setStatus(StatusEnums.VALID.getValue());
        //获取这个用户所在企业相关的用户信息
        Set<Long> userIds = getUserIds(user);
        userIds.add(user.getUserId());
        info.setUserIds(userIds);
        info.setCreateUser(null);
        //根据目录信息获取目录列表
        List<Directory> list = directoryService.getDirectoriesByDirectory(info);
        //json  过滤
        JSONArray object = JsonUtils.parseArray(list);
        resultBean = ResponseUtils.initResultBean(object, Constants.ResponseCode.success, "成功", true);
        logger.info("获取目录信息接口============>>>>>>>>>【结束】");
        return resultBean;
    }
}
